package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class Flink01_Batch_WordCount {
    public static void main(String[] args) throws Exception {
        /**
         * 1.构建spark环境
         * 2.读取数据 textFile
         * 3.使用flatmap算子 将每个单词切出来组成一个Tuple2元组
         * 4.使用reduceBykey按照key（单词）分组，对Tuple2元组中第二个元素求和
         * 5.将结果输出到控制台
         *
         * .stop 关闭资源
         */

        //1.获取Flink的批处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //2.从文件读取数据
        DataSource<String> dataSource = env.readTextFile("input/word.txt");

        //3.使用flatmap算子 将每个单词切出来组成一个Tuple2元组
        FlatMapOperator<String, Tuple2<String, Integer>> wordToOne = dataSource.flatMap((FlatMapFunction<String, Tuple2<String, Integer>>) (value, out) -> {
                String[] words = value.split(" ");
                for (String word : words) {
//                out.collect(new Tuple2<>(word, 1));
                    out.collect(Tuple2.of(word,1));
            }
        }).returns(Types.TUPLE(Types.STRING,Types.INT));

        //4.使用GroupBy按照key（单词）分组，
        UnsortedGrouping<Tuple2<String, Integer>> groupBy = wordToOne.groupBy(0);

        //5.对Tuple2元组中第二个元素求和
        AggregateOperator<Tuple2<String, Integer>> result = groupBy.sum(1);

        //6.将结果打印至控制台
        result.print();

    }

    public static class MyflatMap implements FlatMapFunction<String, Tuple2<String,Integer>>{

        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            String[] words = value.split(" ");
            for (String word : words) {
//                out.collect(new Tuple2<>(word, 1));
                out.collect(Tuple2.of(word,1));
            }
        }
    }
}
